package hw.txtreader;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.io.File;
import java.util.List;

/**
 * 书籍列表适配器
 *
 * @author gaoguanchao
 * @since 2024/11/28
 */
public class ListAdapter extends BaseAdapter {
    private Context mContext;
    private List<Book> mBookList;

    private View.OnClickListener mDelOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int position = (int) view.getTag();
            Book book = mBookList.get(position);
            File file = new File(book.path);
            if (file.delete()) {
                mBookList.remove(position);
            }
            notifyDataSetChanged();
        }
    };

    public ListAdapter(Context context, List<Book> bookList) {
        this.mContext = context;
        this.mBookList = bookList;
    }

    @Override
    public int getCount() {
        return mBookList.size();
    }

    @Override
    public Object getItem(int position) {
        return mBookList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.tvTitle = convertView.findViewById(R.id.book_name);
            viewHolder.tvAuthor = convertView.findViewById(R.id.book_del);
            viewHolder.tvAuthor.setOnClickListener(mDelOnClickListener);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        Book book = mBookList.get(position);
        viewHolder.tvTitle.setText(book.name);
        viewHolder.tvAuthor.setTag(position);
        return convertView;
    }

    static class ViewHolder {
        TextView tvTitle;
        TextView tvAuthor;
    }
}
